<template>
  <div>
    <div style="display: flex; justify-content: space-between">
      <el-breadcrumb
        separator-class="el-icon-arrow-right"
        style="margin-top: 12px; margin-left: 26px"
      >
        <el-breadcrumb-item>
          <span style="color: #409eff; font-size: 15px">生源地图</span>
        </el-breadcrumb-item>
      </el-breadcrumb>

      <div style="display: flex; margin-top: 5px">
        <div
          style="
            margin-top: 3px;
            display: flex;
            width: 450px;
            justify-content: space-between;
          "
        >
          <div style="flex: 1">
            <span style="vertical-align: middle; font-size: 15px">年份：</span>
            <el-select
              v-model="selectConditions.grade"
              placeholder="Select"
              style="width: 100px"
            >
              <el-option
                v-for="item in selectItems.grade"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </div>

          <div style="flex: 2">
            <span style="vertical-align: middle; font-size: 15px">专业：</span>
            <el-select
              v-model="selectConditions.major"
              placeholder="Select"
              style="width: 200px"
            >
              <el-option
                v-for="item in selectItems.major"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </div>
        </div>
      </div>
    </div>
    <section ref="dom" style="width: 100%; height: calc(100% - 30px)"></section>
  </div>
</template>

<script>
import $axios from "@/axios";
import { useStore } from "vuex";
import router from "@/rooter";
import { ref, onMounted, reactive, watch } from "vue";
import { ElMessage } from "element-plus";
import * as echarts from "echarts";
import chinaMap from "@/assets/json/china.json";

export default {
  name: "StudentMap",
  setup() {
    const store = useStore();
    let dom = ref(null);

    // 当前页当前用户权限
    let currentPagePermissionStatusByCurrentUser = reactive({
      mapShow: false,
    });

    let myChart;

    // echarts初始化
    function initEchartMap() {
      // 指定中国地图矢量坐标
      echarts.registerMap("china", { geoJSON: chinaMap });
      myChart = echarts.init(dom.value);

      myChart.setOption({
        tooltip: {
          trigger: "item",
          formatter: function (params) {
            let value = params.value;

            if (isNaN(value)) {
              return params.name + "<br/>暂无数据";
            } else {
              let admissionScore = params.data.admissionScore;
              let averageScoreByCollege = params.data.averageScoreByCollege;
              let averageScoreByMajor = params.data.averageScoreByMajor;

              console.log();
              return (
                params.name +
                "<br/>招生人数：" +
                value +
                "人" +
                "<br/>一本线：" +
                admissionScore +
                "<br/>当前专业平均分：" +
                averageScoreByMajor +
                "<br/>当前专业学院平均分：" +
                averageScoreByCollege
              );
              // return params.name + "<br/>招生人数：" + value + "人";
            }
          },
        },
        toolbox: {
          show: true,
          feature: {
            saveAsImage: {
            },
          },
        },
        visualMap: {
          min: 1,
          max: 8,
          text: ["招生人数"],
          realtime: false,
          calculable: true,
          inRange: {
            color: ["lightskyblue", "yellow", "orangered"],
          },
        },
        series: [
          {
            name: "china",
            type: "map",
            map: "china",
            roam: true, // 是否开启鼠标缩放和平移漫游
            zoom: 1.3, // 当前视角的缩放比例（地图的放大比例）
            top: 120,
            scaleLimit: {
              min: 1.3,
              max: 5,
            },
            itemStyle: {
              // 地图区域的多边形 图形样式。
              areaColor: "#f4f1ea", // 地区默认颜色
              borderWidth: 1, // 边框描绘
              borderColor: "#90c5ed", //片区边框颜色
            },
            emphasis: {
              // 高亮状态下的多边形和标签样式
              areaColor: "#24cbff", // 高亮区域背景颜色
              shadowBlur: 20,
              shadowColor: "rgba(0, 0, 0, 0.5)",
            },
            label: {
              show: true,
            },
            data: enrollmentProviceData.value,
            // 自定义名称映射
            nameMap: {
              安徽省: "安徽",
              澳门特别行政区: "澳门",
              北京市: "北京",
              福建省: "福建",
              甘肃省: "甘肃",
              广东省: "广东",
              广西壮族自治区: "广西",
              贵州省: "贵州",
              海南省: "海南",
              河北省: "河北",
              河南省: "河南",
              黑龙江省: "黑龙江",
              湖北省: "湖北",
              湖南省: "湖南",
              吉林省: "吉林",
              江苏省: "江苏",
              江西省: "江西",
              辽宁省: "辽宁",
              内蒙古自治区: "内蒙古",
              宁夏回族自治区: "宁夏",
              青海省: "青海",
              山东省: "山东",
              山西省: "山西",
              陕西省: "陕西",
              上海市: "上海",
              四川省: "四川",
              台湾省: "台湾",
              天津市: "天津",
              香港特别行政区: "香港",
              新疆维吾尔自治区: "新疆",
              西藏自治区: "西藏",
              云南省: "云南",
              浙江省: "浙江",
              重庆市: "重庆",
            },
          },
        ],
      });

      window.onresize = myChart.resize;
    }

    // 招生省份数据
    let enrollmentProviceData = ref([]);

    // 下拉表可选择内容
    let selectItems = reactive({
      major: ["计算机科学与技术", "软件工程", "网络工程", "大数据与数据科学"],
      grade: [
        "2014",
        "2015",
        "2016",
        "2017",
        "2018",
        "2019",
        "2020",
        "2021",
        "2022",
        "2023",
      ],
    });

    // 下拉列表选择的内容
    let selectConditions = reactive({
      college: "计算机学院",
      major: "计算机科学与技术",
      // grade: new Date().getFullYear() - 1,
      grade: "2020",
    });

    // 监听选择条件的变化
    watch(selectConditions, (newValue) => {
      // 发送请求，获取指定专业,指定年份的招生省份信息
      $axios.post("/province/getProvinceEnrollment", newValue).then((resp) => {
        enrollmentProviceData.value = resp.data.data;

        for (let item of enrollmentProviceData.value) {
          item.name = item.province;
          item.value = item.studentNum;
        }

        let option = myChart.getOption();
        option.series[0].data = enrollmentProviceData.value;
        myChart.setOption(option);
      });
    });

    // 等待vuex中的userPermission准备好
    function waitForPermissions() {
      return new Promise((resolve) => {
        store.watch(
          () => store.state.currentLoginUser.permissions,
          (newValue) => {
            // 权限：
            if (newValue) {
              newValue.forEach((permission) => {
                if (permission.permissionPath === "/originMap") {
                  currentPagePermissionStatusByCurrentUser.mapShow = true;
                }
              });

              // 将 Promise 状态改为已完成
              resolve();
            }
          },
          {
            immediate: true, // 立即监听
          }
        );
      });
    }

    onMounted(async () => {
      await waitForPermissions();

      if (!currentPagePermissionStatusByCurrentUser.mapShow) {
        ElMessage({
          type: "error",
          message: "用户无权限",
          duration: 1500,
        });
        router.go(-1);
        return;
      }

      // 发送请求，获取指定专业,指定年份的招生省份信息
      await $axios
        .post("/province/getProvinceEnrollment", selectConditions)
        .then((resp) => {
          enrollmentProviceData.value = resp.data.data;

          for (let item of enrollmentProviceData.value) {
            item.name = item.province;
            item.value = item.studentNum;
          }
        });

      initEchartMap();
    });

    return {
      dom,
      selectItems,
      selectConditions,
    };
  },
};
</script>

<style>
</style>